<?php

namespace app\common\controller;

use app\common\variable\MsgCode;
use app\common\model\Vip as VipModel;
use app\common\model\VipRule as VipRuleModel;
use app\common\model\VipRuleValue as VipRuleValueModel;
use app\common\model\VipValueAdded as VipValueAddedModel;
use app\common\model\VipValueAddedDiscount as VipValueAddedDiscountModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\UserVipRuleLog as UserVipRuleLogModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\StatusAlias as StatusAliasModel;

/**
 * 
 */
class Vip extends Base
{
    public static function getSelect($where = [], $is_all = false)
    {
        if (!$is_all) {
            $where[] = ['vip.status', '=', 1];
            $where[] = ['vip.price', '>', 0];
            $where[] = ['vip.show', '=', 1];
        }
        $Data = VipModel::alias('vip')
            ->where($where)
            ->field('vip.id,vip.title,vip.icon,vip.price,vip.discount,vip.va_discount,vip.stock,vip.sold,vip.level,vip.surplus_stock,vip.expiry_type,vip.is_company')
            ->withAttr('icon', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->order('vip.is_company asc,vip.level asc')->select()->toArray();
        if (!empty($Data)) {
            foreach ($Data as $k => $v) {
                $Data[$k]['rule'] = VipRuleValueModel::alias('value')
                    ->where(['value.status' => 1])
                    ->join(config('databse.prefix') . 'vip_rule rule', 'rule.rid=value.id AND rule.vid=' . $v['id'], 'LEFT')
                    ->field('rule.vid,rule.rid,rule.id as checked,rule.value,rule.value,value.title,value.unit,value.value as vvalue,value.desc,value.tips,value.type,value.alias')
                    ->withAttr('checked', function ($v, $data) {
                        return 0;
                    })
                    ->withAttr('value', function ($v, $data) {
                        if ($v === null) {
                            return $data['vvalue'];
                        } else {
                            return $v;
                        }
                    })
                    ->select()->toArray();
                $Data[$k]['va'] = VipValueAddedDiscountModel::alias('discount')
                    ->where(['discount.vid' => $v['id']])
                    ->where(['type.alias' => 'vip/value_added_type'])
                    ->join('status_alias type', 'type.value=discount.type')
                    ->field('type.title,discount.discount')->select()->toArray();
            }
        }
        return $Data;
    }
    public static function getCate($where = [])
    {
        $where[] = ['vip.status', '=', 1];
        $Data = VipModel::alias('vip')
            ->where($where)
            ->field('vip.id,vip.title,vip.level,vip.is_company,vip.icon,vip.price,vip.discount,vip.va_discount,vip.stock,vip.sold,vip.surplus_stock')
            ->withAttr('icon', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : '';
            })
            ->order('vip.is_company desc,vip.level asc')->select();
        return $Data;
    }
    public static function getFind($id)
    {
        $where[] = ['vip.status', '=', 1];
        $where[] = ['vip.price', '>', 0];
        $Find = VipModel::alias('vip')
            ->where($where)
            ->field('vip.id,vip.title,vip.icon,vip.price,vip.discount,vip.va_discount,vip.stock,vip.sold,vip.surplus_stock')
            ->withAttr('icon', function ($v, $data) {
                return $v ? config('web.imgurl') . $v : '';
            })->find();
        if (!$Find) {
            $Find->rule = VipRuleValueModel::alias('value')
                ->where(['value.status' => 1])
                ->join(config('databse.prefix') . 'vip_rule rule', 'rule.rid=value.id AND rule.vid=' . $Find['id'], 'LEFT')
                ->field('rule.value,rule.value,value.title,value.unit,value.value as vvalue,value.desc,value.tips,value.type,value.alias')
                ->withAttr('value', function ($v, $data) {
                    if ($v === null) {
                        return $data['vvalue'];
                    } else {
                        return $v;
                    }
                })
                ->select();
            $Find->va = VipValueAddedDiscountModel::alias('discount')
                ->where(['discount.vid' => $Find['id']])
                ->where(['type.alias' => 'vip/value_added_type'])
                ->join('status_alias type', 'type.value=discount.type')
                ->field('type.title,discount.discount')->select();
        }
        return $Find;
    }
    public static function getValueAdded($D = [])
    {
        $UserVipModel = UserVipModel::where(['uid' => $D['uid']])->find();
        $CompanyVipLevel = 0;
        $PersonalVipLevel = 0;
        if ($UserVipModel) {
            $CompanyVipLevel = $UserVipModel->company_vip_level;
        } else {
            $PersonalVipLevel = $UserVipModel->persona_vip_level;
        }
        $CompanyDiscount = VipValueAddedDiscountModel::alias('discount')
            ->where(['type.alias' => 'vip/value_added_type', 'type.is_company' => 1])
            ->join('status_alias type', 'type.value=discount.type')
            ->where([['discount.discount', '>', 0], ['vip.level', '=', $CompanyVipLevel]])
            ->join('vip vip', 'vip.id=discount.vid AND vip.status=1 AND vip.price>0')
            ->field('discount.type,discount.discount')->order('discount.discount asc')->column('discount.discount', 'discount.type');
        $PersonalDiscount = VipValueAddedDiscountModel::alias('discount')
            ->where(['type.alias' => 'vip/value_added_type', 'type.is_company' => 0])
            ->join('status_alias type', 'type.value=discount.type')
            ->where([['discount.discount', '>', 0], ['vip.level', '=', $PersonalVipLevel]])
            ->join('vip vip', 'vip.id=discount.vid AND vip.status=1 AND vip.price>0')
            ->field('discount.type,discount.discount')->order('discount.discount asc')->column('discount.discount', 'discount.type');
        $company_download_resume = [];
        $company_time_refresh = [];
        $company_jobs_top = [];
        $company_urgent = [];
        $resume_top = [];
        $resume_refresh = [];
        $va = VipValueAddedModel::alias('va')->where(['va.status' => 1])
            ->where(['type.alias' => 'vip/value_added_type'])
            ->join('status_alias type', 'type.value=va.type')
            ->order('va.level asc,va.id asc')
            ->field('va.id,va.type as discount,va.type,va.title,va.value,va.price,type.type as unit,type.is_company')->select();
        foreach ($va as $k => $item) {
            $item->ordinary = 0;
            $ordinary = VipModel::alias('vip')->where(['vip.level' => 0])
                ->join('vip_value_added_discount discount', 'discount.vid=vip.id AND discount.type=' . $item->discount)
                ->value('discount.discount');
            if ($ordinary)
                $item->ordinary = $ordinary;
            $item->vip = 0;
            if ($item->is_company) {
                $vip = VipModel::alias('vip')->where(['vip.level' => $CompanyVipLevel])
                    ->join('vip_value_added_discount discount', 'discount.vid=vip.id AND discount.type=' . $item->discount)
                    ->value('discount.discount');
                if ($vip) $item->vip = $vip;
            } else {
                $vip = VipModel::alias('vip')->where(['vip.level' => $PersonalVipLevel])
                    ->join('vip_value_added_discount discount', 'discount.vid=vip.id AND discount.type=' . $item->discount)
                    ->value('discount.discount');
                if ($vip) $item->vip = $vip;
            }
            switch ($item->type) {
                case 2:
                    $company_download_resume[] = $item;
                    break;
                case 4:
                    $company_jobs_top[] = $item;
                    break;
                case 5:
                    $company_urgent[] = $item;
                    break;
                case 7:
                    $company_time_refresh[] = $item;
                    break;
                case 8:
                    $resume_top[] = $item;
                    break;
                case 9:
                    $resume_refresh[] = $item;
                    break;
            }
        }
        $Data = [
            'download_resume'   =>  [
                'title'     =>  '简历包',
                'tips'      =>  '简历打包购买更实惠，VIP会员购买可享最低{discount}优惠',
                'discount'  =>  empty($CompanyDiscount[2]) ? 0 : $CompanyDiscount[2],
                'type'      =>  2,
                'data'      =>  $company_download_resume
            ],
            'time_refresh'   =>  [
                'title'     =>  '智能刷新',
                'tips'      =>  '让职位随时名列前茅,在同类信息中崭露头角，VIP会员购买最低享受{discount}优惠',
                'discount'  =>  empty($CompanyDiscount[7]) ? 0 : $CompanyDiscount[7],
                'type'      =>  7,
                'data'      =>  $company_time_refresh
            ],
            'jobs_top'   =>  [
                'title'     =>  '职位置顶',
                'tips'      =>  '职位置顶让你的职位始终名列前茅。VIP会员可享最低{discount}优惠',
                'discount'  =>  empty($CompanyDiscount[4]) ? 0 : $CompanyDiscount[4],
                'type'      =>  4,
                'data'      =>  $company_jobs_top
            ],
            'urgent'   =>  [
                'title'     =>  '紧急招聘',
                'tips'      =>  '急招不用苦等，职位加急，为职位增加曝光量。VIP会员可享最低{discount}优惠',
                'discount'  =>  empty($CompanyDiscount[5]) ? 0 : $CompanyDiscount[5],
                'type'      =>  5,
                'data'      =>  $company_urgent
            ],
            'resume_top'   =>  [
                'title'     =>  '简历置顶',
                'tips'      =>  '为简历增加曝光量。VIP会员可享最低{discount}优惠',
                'discount'  =>  empty($PersonalDiscount[8]) ? 0 : $PersonalDiscount[8],
                'type'      =>  8,
                'data'      =>  $resume_top
            ],
            'resume_refresh'   =>  [
                'title'     =>  '简历刷新',
                'tips'      =>  '为简历增加曝光量。VIP会员可享最低{discount}优惠',
                'discount'  =>  empty($PersonalDiscount[9]) ? 0 : $PersonalDiscount[9],
                'type'      =>  9,
                'data'      =>  $resume_refresh
            ],
        ];
        return $Data;
    }
    public static function getMyRights($D)
    {
        $Data = UserVipRuleModel::alias('rule')->where(['rule.uid' => $D['uid']])
            ->join('vip vip', 'vip.id=rule.vid', 'LEFT')
            ->join('vip_rule_value value', 'value.id=rule.rid', 'LEFT')
            ->join('user_vip user_vip', 'user_vip.uid=rule.uid', 'LEFT')
            ->field('rule.value,rule.vid,rule.status,rule.surplus_value,rule.expiry_time,rule.expiry_type,rule.is_company,rule.create_time,vip.title as vip_name,rule.rid,value.title as rule_name,value.unit,value.alias,user_vip.company_vip_level,user_vip.personal_vip_level,user_vip.company_vip_time,user_vip.personal_vip_time')
            ->order('rule.status desc,rule.expiry_time asc,rule.surplus_value desc,rule.level asc')->paginate(15)->each(function ($v) use ($D) {
                if ($v->expiry_type || !$v->vid) {
                    $v->is_expiry = $v['expiry_time'] > time() ? 0 : 1;
                    $v->expiry_time = date('Y-m-d', $v['expiry_time']);
                } else {
                    $expiry_time = $v->expiry_time;
                    if ($v->is_company) {
                        if ($v->company_vip_level)
                            $expiry_time = $v->company_vip_time;
                    } else {
                        if ($v->personal_vip_level)
                            $expiry_time = $v->personal_vip_time;
                    }
                    $v->is_expiry = $expiry_time > time() ? 0 : 1;
                    $v->expiry_time = date('Y-m-d', $expiry_time);
                }
                if ($v->alias == 'release-jobs') {
                    $surplus_value = $v['surplus_value'] - JobsModel::where(['company_id' => $D['company_id']])->whereNull('delete_time')->count();
                    $v->surplus_value = $surplus_value > 0 ? $surplus_value : 0;
                }
                if (!$v->vid) {
                    $value = VipValueAddedModel::alias('va')->where(['va.id' => $v->rid])
                        ->where(['type.alias' => 'vip/value_added_type'])
                        ->join(config('databse.prefix') . 'status_alias type', 'type.value=va.type')
                        ->field('va.title,type.type as unit')->find();
                    if ($value) {
                        $v->rule_name = $value->title;
                        $v->unit = $value->unit;
                    }
                }
            });
        if ($Data->items()) {
            return parent::ajaxReturn('', MsgCode::$success, $Data);
        } else {
            return parent::ajaxReturn('暂无数据~', MsgCode::$error);
        }
    }
    public static function getMyRightsDetailed($D)
    {
        $DataObj = UserVipRuleLogModel::where(['uid' => $D['uid']]);
        if (!empty($D['time'][0]) && !empty($D['time'][1])) {
            $whereTime = [round($D['time'][0] / 1000), round($D['time'][1] / 1000)];
            $DataObj->whereTime('create_time', 'between', $whereTime);
        }
        $Data = $DataObj->order('id desc')->paginate(15)->each(function ($v) {
        });;
        if ($Data->items()) {
            return parent::ajaxReturn('', MsgCode::$success, $Data);
        } else {
            return parent::ajaxReturn('暂无数据~', MsgCode::$error);
        }
    }
}
